//    Copyright (C) Kherty.  All rights reserved.
using System;

namespace OpenLS.Spreadsheet
{
    class NameNode: RangeNodeBase
    {
        public NameNode(string name)
        {
            Name = name;
        }

        public string Name { get; private set; }
        

        internal void Touch()
        {
            var chain = new CalculationChain(this);
            chain.Calculate();
        }

        internal void UpdateRange(NameManager manager)
        {
            foreach (DefinedName definedName in manager.definedNames)
                if (definedName.Name == Name)
                {
                    var range = definedName.Value as Range;
                    if (range != null)
                    {
                        RefersTo = range.Worksheet.RangeManager.GetNode(range);
                        return;
                    }
                }
            RefersTo = null;
        }

        internal void UpdateRange(TableNameManager manager)
        {
            foreach (DefinedName definedName in manager.tableDefinedNames)
                if (definedName.Name == Name)
                {
                    var range = definedName.Value as Range;
                    if (range != null)
                    {
                        RefersTo = range.Worksheet.RangeManager.GetNode(range);
                        return;
                    }
                }
            RefersTo = null;
        }

        private RangeNode _rangeNode;
        private RangeNode RefersTo
        {
            get { return _rangeNode; }
            set
            {
                if (_rangeNode != null)
                    _rangeNode.RemoveDependent(this);
                _rangeNode = value;
                if (_rangeNode != null)
                    _rangeNode.AddDependent(this);
            }
        }
    }
}


